package org.rc.web;

import com.google.gson.Gson;
import org.rc.dao.RaceDao;
import org.rc.dao.ResultDao;
import org.rc.model.Race;
import org.rc.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Race servlet
 *
 */
public class RaceServlet extends IndexServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(RaceServlet.class);
    private RaceDao raceDao = new RaceDao();
    private ResultDao resultDao = new ResultDao();

    /**
     * Show the race results page. If its an ajax request then send back a page of results
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        String idParam = request.getParameter("id");
        if(idParam!=null) {
            redirectToRacePage(idParam, request, response);
        } else {
            idParam = request.getParameter("ajaxraceid");
            String cursor = request.getParameter("cursor");
            Race race = loadRace(idParam);
            List<Result> results = new ArrayList<Result>();
            cursor = resultDao.getResultsForRace(results, race, cursor, 500);
            response.setContentType("applicaiton/json");
            Gson gson = new Gson();
            LOGGER.info("returning page size" + results.size());
            response.getWriter().write(gson.toJson(new InfiniteScrollPage(cursor,results)));
        }
    }

    /**
     * Redurect to the view for the race page.
     * @param idParam
     * @param request
     * @param response
     */
    private void redirectToRacePage(String idParam, HttpServletRequest request, HttpServletResponse response) {
        Race race = loadRace(idParam);
        request.setAttribute("race", race);
        request.setAttribute("sameDistRaces", raceDao.getRacesForDistance(race.getDistanceM()));
        forward(request, response, "race.jsp");
    }

    private Race loadRace(String idString) {
        Long id = null;
        try {
            id = new Long(idString);
        } catch(NumberFormatException e) {
            LOGGER.error("invalid param", idString);
        }
        LOGGER.debug("Loading race with ID:"+id);
        Race race = (Race) cache.get("race"+id);
        if(race==null) {
            race = raceDao.get(id);
            cache.put("race"+id, race);
        }
        return race;
    }
}
